package com.itheima.service.impl;

import com.itheima.common.utils.DateUtils;
import com.itheima.common.utils.POIUtils;
import com.itheima.mapper.OrderSettingMapper;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.Servlet;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;

@Service
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingMapper orderSettingMapper;

    /**
     * 导出预约模板
     * @param response
     */
    @Override
    public void export(HttpServletResponse response,String filename) {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("templates/"+filename);
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            out.flush();
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 上传文件
     * @param excelFile
     */
    @Override
    public void upload(MultipartFile excelFile) {
        try {
            List<String[]> list = POIUtils.readExcel(excelFile);
            for (String[] strings : list) {
                String date = strings[0];
                String number = strings[1];
                OrderSetting orderSetting = new OrderSetting(DateUtils.parseString2Date(date,"yyyy/MM/dd"),Integer.parseInt(number));
                orderSettingMapper.insert(orderSetting);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据年月查询对应的预约设置信息
     * @param month
     * @return
     */
    @Override
    public List<OrderSetting> getOrderSettingByMonth(String month) {
        String[] times = month.split("-");
        LocalDate begindate = LocalDate.of(Integer.parseInt(times[0]), Integer.parseInt(times[1]), 1);
        LocalDate enddate = begindate.plusMonths(1);
        List<OrderSetting> list = orderSettingMapper.getOrderSettingByMonth(begindate,enddate);
        return list;
    }

    /**
     * 根据日期修改可预约人数
     * @param orderSetting
     */
    @Override
    public void editNumberByOrderDate(OrderSetting orderSetting) {
        orderSettingMapper.update(orderSetting);
    }
}
